package com.training.utils;

import javax.crypto.SecretKey;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;

public class RSAUtil {
    
    private static final String ALGORITHM = "RSA";
    private static final String TRANSFORMATION = "RSA/ECB/PKCS1Padding";
    
    /**
     * 从Base64字符串加载公钥
     * @param publicKeyStr Base64编码的公钥字符串
     * @return PublicKey对象
     * @throws Exception 解析异常
     */
    public static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(publicKeyStr);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        return keyFactory.generatePublic(spec);
    }
    
    /**
     * 使用RSA公钥加密AES密钥
     * @param aesKey AES密钥
     * @param publicKey RSA公钥
     * @return 加密后的AES密钥（Base64编码）
     * @throws Exception 加密异常
     */
    public static String encryptAESKey(SecretKey aesKey, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedKey = cipher.doFinal(aesKey.getEncoded());
        return Base64.getEncoder().encodeToString(encryptedKey);
    }
    
    /**
     * 使用RSA公钥加密AES密钥字符串
     * @param aesKeyStr AES密钥字符串
     * @param publicKey RSA公钥
     * @return 加密后的AES密钥（Base64编码）
     * @throws Exception 加密异常
     */
    public static String encryptAESKey(String aesKeyStr, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedKey = cipher.doFinal(aesKeyStr.getBytes());
        return Base64.getEncoder().encodeToString(encryptedKey);
    }
}